import {
  login,
} from '/service/service'
import CryptoJS from 'crypto-js';
import JSEncrypt from 'jsencrypt';
import {
  getDdAccessToken,
  getDdInnerMiniAppsVersions
} from '/service/dd_service';

Page({
  data: {
    // 密码登录false;快速登录true
    rotateRight: false,
    quickLoginInfo: {},
    isPassword: true,
    aesKey: '',
    version: '',
    tenantOptions: ['江北公安', '鄞州公安'],
    tenantName: '江北公安',
    showQuickLoginBtn: false,
    inputFocus: {
      username: false,
      password: false
    },
    // 输入框内容
    formData: {
      username: '',
      password: '',
      tenantId: '000000'
    },
    currentFocusType: ''
  },
  onLoad(query) {
    const userLoginInfo = my.getStorageSync({
      key: 'user_login_info'
    }).data;

    if (userLoginInfo) {
      this.setData({
        rotateRight: true,
        tenantName: userLoginInfo.tenantName,
        quickLoginInfo: userLoginInfo,
        showQuickLoginBtn: !!userLoginInfo.username && !!userLoginInfo.password
      })
    }
  },
  handleInput(e) {
    const type = e.currentTarget.dataset.type;
    const value = e.detail.value;

    // 更新表单数据
    this.setData({
      [`formData.${type}`]: value,
      // 有内容时激活标签状态
      [`inputFocus.${type}`]: this.data.currentFocusType === type
    });
  },
  handleFocus(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      [`inputFocus.${type}`]: true,
      currentFocusType: type // 记录当前聚焦的输入框
    });
  },

  /**
   * 输入框失焦事件
   */
  handleBlur(e) {
    const type = e.currentTarget.dataset.type;
    const value = this.data.formData[type];

    this.setData({
      [`inputFocus.${type}`]: value.trim() !== '', // 失焦后根据内容判断
      currentFocusType: '' // 清空聚焦记录
    });
  },
  async getVersion() {
    const {
      status,
      data
    } = await getDdAccessToken()
    if (status === 200) {
      const {
        accessToken
      } = data
      if (data) {
        const res = await getDdInnerMiniAppsVersions(accessToken)
        if (res.status === 200 && res.data) {
          const appVersionList = res.data.appVersionList
          if (appVersionList && appVersionList.length > 0) {
            // console.log('小程序版本：', appVersionList[0].appVersion)
          }
        }
      }
    }
  },
  getTenantId(tenantName) {
    const map = {
      '江北公安': '000000',
      '鄞州公安': '040789'
    }
    return map[tenantName] || '000000'
  },
  handleRef(ref) {
    this.form.addItem(ref);
    // if (ref.props.name === 'tenantName') {
    //   console.log('aa')
    // }
  },
  switchStatus() {
    this.setData({
      isPassword: !this.data.isPassword
    })
  },
  // 生成随机UUID
  randomUUID() {
    const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
    const uuid = new Array(36);
    let rnd = 0;
    let r;

    for (let i = 0; i < 36; i++) {
      if (i === 8 || i === 13 || i === 18 || i === 23) {
        uuid[i] = "-";
      } else if (i === 14) {
        uuid[i] = "4";
      } else {
        if (rnd <= 0x02) rnd = (0x2000000 + Math.random() * 0x1000000) | 0;
        r = rnd & 0xf;
        rnd = rnd >> 4;
        uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r];
      }
    }
    return uuid.join("").replace(/-/gm, "").toLowerCase();
  },
  // 生成AES密钥
  generateAesKey() {
    this.data.aesKey = CryptoJS.enc.Utf8.parse(this.randomUUID());
  },
  // 加密AES密钥为Base64
  encryptBase64() {
    return CryptoJS.enc.Base64.stringify(this.data.aesKey);
  },
  // 使用公钥加密AES密钥
  encrypt() {
    const instance = new JSEncrypt();
    // 公钥
    instance.setPublicKey("MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKoR8mX0rGKLqzcWmOzbfj64K8ZIgOdHnzkXSOVOZbFu/TJhZ7rFAN+eaGkl3C4buccQd/EjEsj9ir7ijT7h96MCAwEAAQ==");
    return instance.encrypt(this.encryptBase64());
  },
  // 加密登录数据
  encryptData(values) {
    const data = {
      username: values.username,
      password: values.password,
      clientId: "e5cd7e4891bf95d1d19206ce24a7b32e",
      tenantId: this.getTenantId(values.tenantName),
      grantType: "password"
    };

    // AES加密
    const encrypted = CryptoJS.AES.encrypt(
      JSON.stringify(data),
      this.data.aesKey, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      }
    );

    return encrypted.toString();
  },
  showToast(title, type = 'none') {
    my.showToast({
      content: title,
      type: type,
      duration: 1500
    });
  },
  async submit(e) {
    const {
      flag
    } = e.currentTarget.dataset;
    const STORAGE_KEYS = {
      TOKEN: 'token',
      USER_LOGIN_INFO: 'user_login_info'
    };
    const REDIRECT_URL = '/pages/home/home';
    const DEFAULT_TENANT_ID = '000000';

    try {
      let loginParams, needSaveUserInfo = false;

      switch (flag) {
        case 'username':
          const {
            formData
          } = this.data
          if (formData.username.trim() === '') {
            return dd.showToast({
              content: '用户名不能为空',
              type: 'fail'
            })
          }
          if (formData.password.trim() === '') {
            return dd.showToast({
              content: '密码不能为空',
              type: 'fail'
            })
          }
          // console.log(formData)
          // const values = await this.form.submit();
          loginParams = formData;
          needSaveUserInfo = true;
          break;

        case 'quick':
          loginParams = Object.assign({}, this.data.quickLoginInfo, {
            tenantId: DEFAULT_TENANT_ID
          });
          break;

        default:
          return dd.showToast({
            content: '登录方式不支持',
            type: 'fail'
          });
      }

      // 加密+登录请求（核心逻辑完）
      this.generateAesKey();
      const encryptedData = this.encryptData(loginParams);
      const headers = {
        "encrypt-key": this.encrypt()
      };
      const res = await login(encryptedData, headers);

      if (res && res.access_token) {
        // 存储token（保留原逻辑）
        my.setStorageSync({
          key: STORAGE_KEYS.TOKEN,
          data: res.access_token
        });

        // 账号登录时保存用户信息（保留原存储字段）
        if (needSaveUserInfo) {
          my.setStorageSync({
            key: STORAGE_KEYS.USER_LOGIN_INFO,
            data: {
              username: loginParams.username,
              password: loginParams.password,
              tenantName: loginParams.tenantName
            }
          });
        }

        my.reLaunch({
          url: REDIRECT_URL,
          // url: '/pages/newLogin/newLogin'
        });
      }
    } catch (error) {
      console.error('登录失败:', error);
      const errorMsg = error.message || '';
      if (errorMsg.includes('Password') || errorMsg.includes('密码输入错误')) {
        this.showToast('密码错误');
      } else if (errorMsg.includes('does not exist') || errorMsg.includes('不存在')) {
        this.showToast('用户名不存在');
      } else {
        this.showToast('error');
      }
    }
  },
  // 切换到快速登录（朝右旋转）
  toQuickLogin() {
    this.setData({
      rotateRight: true
    });
  },

  // 切换到账户登录（朝左旋转，恢复初始状态）
  toAccountLogin() {
    this.setData({
      rotateRight: false
    });
  },

  clearUsername() {
    this.setData({
      'formData.username': '',
      'inputFocus.username': false
    })
  }
});